/*
 * @Author: lwHao
 * @Date: 2021-05-25 14:40:11
 * @LastEditors: liwenhao
 * @LastEditTime: 2021-05-25 21:44:18
 */

class Node {
  constructor(element, next) {
    this.element = element
    this.next = next
  }
}
class LinkedList {
  constructor() {
    this.head = null
    this.size = 0
  }
  _getNode(index){
    if (index <0 || index >= this.size) {
      throw new Error('越界了')
    }
    let currentNode = this.head
    for (let i=0; i <index; i++) {
      currentNode = currentNode.next
    }
    return currentNode
  }
  add(index,element){
    if(arguments.length===1){
      element = index
      index = this.size
    }
    if (index === 0) {
      let head = this.head
      this.head = new Node(element, head)
    } else {
      let currentNode = this._getNode(index)
      currentNode = new Node(element, currentNode)
    }
    this.size++
  }
  remove(index){
    if (index <0 || index >= this.size) {
      throw new Error('越界了')
    }
    if (index === 0) {
      let head = this.head
      this.head = head.next
    } else {
      let prevNode = this._getNode(index - 1)
      prevNode.next = prevNode.next.next
    }
    this.size--
  }
}

let l1 = new LinkedList()
l1.add('abc')
l1.add(0,'def')
console.log(l1);
l1.remove(1)
console.log(l1);